package serverside;

import java.io.BufferedReader;
import java.io.IOException;
import java.security.Key;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JOptionPane;
import sun.misc.BASE64Decoder;

//represent the Keypad of the ATM 
public class Keypad {

    private BufferedReader inFromClient;
    private Scanner input;
    private static final byte[] keyValue = new byte[]{'T', 'h', 'e', 'B', 'e',
        's', 't', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};

    //no-argument constructor intializes the scanner 
    public Keypad(BufferedReader reader) {
        inFromClient = reader;
        input = new Scanner(System.in);
    }// end no-arguments Keypad constructor 

    // return an integer value entered by user
    public String getInput() {
        try {
            return Decrypt(inFromClient.readLine());//we asumes that user enters an integers 
        } catch (IOException ex) {
            System.out.println("An error occured in getting input from clirnt");
            System.out.print("If you want to view error send 1 or 0 otherwise");
            if (input.nextInt() == 1) {
                JOptionPane.showMessageDialog(null, "Error", ex.getMessage(), JOptionPane.ERROR_MESSAGE);
            }
            return "Error";
        }
    }

    //decryption function
    private static String Decrypt(String encryptedData) {
        try {
            Key key = generateKey();
            
            Cipher c = Cipher.getInstance("AES");
            c.init(Cipher.DECRYPT_MODE, key);
            
            byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
            byte[] decValue = c.doFinal(decordedValue);
            
            String decryptedValue = new String(decValue);
            return decryptedValue;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }
    
       private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, "AES");
        return key;
    }
}//end class Keypad

